package com.wang.tool.monitor.aop;

import com.wang.tool.monitor.MonitorConfigCenter;
import com.wang.tool.monitor.core.LinkTransmitter;
import com.wang.tool.monitor.log.LogApi;
import com.wang.tool.monitor.callback.MonitorCallback;
import com.wang.tool.monitor.translator.ErrorTranslator;
import com.wang.tool.monitor.weaver.TypeWeaver;
import com.wang.tool.monitor.writer.MonitorWriter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @Description
 * @Author shaopeng
 * @Date 2022/11/4
 * @Version 1.0
 */
public class SpringMonitorConfigSetter implements ApplicationContextAware {
    public static final String SPRING_LINK_TRANSMITTER_NAME = "springLinkTransmitterName";
    public static final String SPRING_LOG_API_NAME = "springLogApiName";
    public static final String SPRING_GLOBAL_ERROR_TRANSLATOR_NAME = "springGlobalErrorTranslator";
    public static final String SPRING_GLOBAL_MONITOR_WRITER_NAME = "springGlobalMonitorWriter";
    public static final String SPRING_MONITOR_CALLBACK_NAME = "springMonitorCallbackName";
    public static final String SPRING_TYPE_WEAVER_NAME_PREFIX = "springTypeWeaverName_";



    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (applicationContext.containsBean(SPRING_LINK_TRANSMITTER_NAME)) {
            MonitorConfigCenter.setLinkTransmitter(applicationContext.getBean(SPRING_LINK_TRANSMITTER_NAME, LinkTransmitter.class));
        }
        if (applicationContext.containsBean(SPRING_LOG_API_NAME)) {
            MonitorConfigCenter.setLogApi(applicationContext.getBean(SPRING_LOG_API_NAME, LogApi.class));
        }
        if (applicationContext.containsBean(SPRING_GLOBAL_ERROR_TRANSLATOR_NAME)) {
            MonitorConfigCenter.setTranslator(applicationContext.getBean(SPRING_GLOBAL_ERROR_TRANSLATOR_NAME, ErrorTranslator.class));
        }
        if (applicationContext.containsBean(SPRING_GLOBAL_MONITOR_WRITER_NAME)) {
            MonitorConfigCenter.setMonitorWriter(applicationContext.getBean(SPRING_GLOBAL_MONITOR_WRITER_NAME, MonitorWriter.class));
        }
        if (applicationContext.containsBean(SPRING_MONITOR_CALLBACK_NAME)) {
            MonitorConfigCenter.setMonitorCallback(applicationContext.getBean(SPRING_MONITOR_CALLBACK_NAME, MonitorCallback.class));
        }

        int i = 0;
        while (applicationContext.containsBean(SPRING_TYPE_WEAVER_NAME_PREFIX+i)){
            MonitorConfigCenter.installTypeWeaver(applicationContext.getBean(SPRING_TYPE_WEAVER_NAME_PREFIX+i, TypeWeaver.class));
            i++;
        }

    }
}
